#!/usr/bin/python
#-*- coding: UTF-8 -*-
# 批量从某段IP中找出指定域名是否对应
import httplib

headers= {}
headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
headers['Accept-Charset'] = 'UTF-8,*;q=0.5'
headers['Accept-Language'] = 'zh-CN,zh;q=0.8,en;q=0.6'
headers['Connection'] = 'keep-alive'
headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11'

INIT = {}
INIT['domain'] = 'drive.google.com'
INIT['path'] = '/'
INIT['succ_ip'] = '203.208.46.1'
INIT['fail_ip'] = None
INIT['timeout'] = 1

def testDomain(domain = INIT['domain'], ip=INIT['succ_ip'], path = INIT['path']):
    wrt = ''
    try:
        conn = httplib.HTTPConnection(ip, timeout=INIT['timeout'])
        headers['Host'] = domain
        conn.request('GET',path , '', headers)
        res = conn.getresponse()
        wrt = res.read()
        res.close()
        conn.close()
    except (Exception), e:
        if e  == 'time out':
            wrt = None
    finally:
        return wrt

def main():

    """docstring for main"""
    ip_prefix = '203.208.46.'
    result = []

    succ_res = testDomain()
    fail_res = 'bigotry'
    for ip_suffix in range(1, 255):
        test_ip = ip_prefix + str(ip_suffix)
        test_res = testDomain(ip = test_ip)
        print 'testing:', test_ip, 
        if test_res and (succ_res == test_res or fail_res != test_res):
            result.append(test_ip + '\t' + INIT['domain'])
            print 'YES'
        else:
            print test_res or 'TIMEOUT'
    print '-'*20
    print '- RESULT'
    print '-'*20
    print 'available:', len(result)
    for record in result: print record
    print '-'*20


if __name__ == '__main__':
    main()
